<template>
  <!-- 直接使用路由模式 -->
  <!-- <van-tabbar route>
    <van-tabbar-item
      v-for="(item, index) in items"
      :key="index"
      :icon="item.icon"
      :to="item.to"
    >
      {{ item.text }}
            </van-tabbar-item>
  </van-tabbar> -->

  <van-tabbar v-model="active" :fixed="false" @change="onChange">
    <van-tabbar-item
      v-for="(item, index) in items"
      :key="index"
      :icon="item.icon"
    >
      {{ item.text }}
    </van-tabbar-item>
  </van-tabbar>
</template>

<script lang="ts" setup>
import { ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";

const route = useRoute();
const router = useRouter();

// console.log("route", route);
// console.log("route.name", route.name);

const items = [
  {
    icon: "home-o",
    text: "电影",
    to: { name: "film-list" },
  },
  {
    icon: "search",
    text: "影院",
    to: { name: "cinema-list" },
  },
  {
    icon: "friends-o",
    text: "资讯",
    to: { name: "post", url: `${import.meta.env.BASE_URL}/post.html` },
  },
  {
    icon: "setting-o",
    text: "我的",
    to: { name: "center" },
  },
];

// 当前激活的下标
const active = ref(0);

// 监听 route.name 匹配 items 的下标，修改 active。让刷新的时候也能正确的高亮显示当前的 item
watch(
  () => route,
  (newVal) => {
    // console.log("route.name 改变了", newVal);
    // active.value = items.findIndex((item) => item.to.name === newVal);

    // newVal.matched; // [{}, {}]
    const names = newVal.matched.map((item) => item.name);
    active.value = items.findIndex((item) => names.includes(item.to.name));
  },
  {
    immediate: true,
  }
);

function onChange(active: number) {
  // 通过 active 匹配 items 中具体的一项
  const to = items[active].to;
  console.log("to", to);

  if (to.url) {
    location.href = to.url;
  } else {
    // 使用 router.replace() 跳转
    router.replace(to);
  }
}
</script>
